package cn.itcast.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;

/**
 * 获取redis连接对象
 */
@Configuration  //表示配置文件，包含一个个bean对象，项目启动会优先加载配置文件，会把bean对象置于容器
public class RedisClusterConfig {
    /**
     * redis.maxtotal
     * redis.minIdle
     * redis.maxIdle
     * redis.address = node01:7001,node01:7002,node01:7003
     */
    @Value("${redis.maxtotal}")
    private int maxtotal;
    @Value("${redis.minIdle}")
    private int minIdle;
    @Value("${redis.maxIdle}")
    private int maxIdle;
    @Value("${redis.address}")
    private String address;



    @Bean //spring将当前方法返回值以指定名称存储到spring容器
    public JedisCluster getJedis(){
        //设置连接池
        GenericObjectPoolConfig pool = new GenericObjectPoolConfig();
        pool.setMaxTotal(maxtotal);
        pool.setMinIdle(minIdle);
        pool.setMaxIdle(maxIdle);
        String[] arr = address.split(",");
        HashSet<HostAndPort> nodes = new HashSet<>();
        for (String s : arr) {
            String[] host_port = s.split(":");
            nodes.add(new HostAndPort(host_port[0], Integer.parseInt(host_port[1])));
        }
        JedisCluster jedisCluster = new JedisCluster(nodes,pool);
        return jedisCluster;
    }
}
